import React, { useRef, useState } from 'react';
import { useFrame } from '@react-three/fiber';
import { Text, Box, Cylinder, Sphere } from '@react-three/drei';
import { ProfileBubble } from '../ProfileBubble';
import type { DatingProfile } from '../../types';
import * as THREE from 'three';

// Interactive candle with flame animation
const InteractiveCandle: React.FC<{ position: [number, number, number] }> = ({ position }) => {
  const flameRef = useRef<THREE.Mesh>(null);
  const [lit, setLit] = useState(true);
  
  useFrame((state) => {
    if (flameRef.current && lit) {
      const flicker = 0.5 + Math.sin(state.clock.elapsedTime * 8) * 0.1;
      flameRef.current.scale.setScalar(flicker);
      flameRef.current.position.y = position[1] + 0.16 + Math.sin(state.clock.elapsedTime * 12) * 0.02;
    }
  });

  return (
    <group 
      position={position}
      onClick={() => setLit(!lit)}
      onPointerOver={(e) => { e.stopPropagation(); }}
    >
      {/* Candle */}
      <Cylinder
        args={[0.02, 0.02, 0.15, 8]}
        castShadow
      >
        <meshLambertMaterial color="#FFE4B5" />
      </Cylinder>
      {/* Flame */}
      {lit && (
        <Sphere
          ref={flameRef}
          position={[0, 0.16, 0]}
          args={[0.02]}
        >
          <meshLambertMaterial 
            color="#FFA500" 
            emissive="#FFA500" 
            emissiveIntensity={0.8}
          />
        </Sphere>
      )}
      {/* Wax drip */}
      {lit && (
        <Sphere
          position={[0, 0.05, 0]}
          args={[0.015, 0.015, 0.03, 8]}
        >
          <meshLambertMaterial color="#FFFAF0" transparent opacity={0.8} />
        </Sphere>
      )}
    </group>
  );
};

// Rotating wine bottle
const RotatingWine: React.FC<{ position: [number, number, number], color: string }> = ({ position, color }) => {
  const bottleRef = useRef<THREE.Mesh>(null);
  const [hovered, setHovered] = useState(false);
  
  useFrame(() => {
    if (bottleRef.current && hovered) {
      bottleRef.current.rotation.y += 0.02;
    }
  });

  return (
    <Cylinder
      ref={bottleRef}
      position={position}
      args={[0.03, 0.04, 0.25, 8]}
      castShadow
      onPointerOver={() => setHovered(true)}
      onPointerOut={() => setHovered(false)}
    >
      <meshLambertMaterial 
        color={color} 
        transparent 
        opacity={hovered ? 0.9 : 0.7}
        emissive={hovered ? color : '#000000'}
        emissiveIntensity={hovered ? 0.1 : 0}
      />
    </Cylinder>
  );
};

interface RestaurantSceneProps {
  profiles: DatingProfile[];
  onProfileClick: (profile: DatingProfile) => void;
}

export const RestaurantScene: React.FC<RestaurantSceneProps> = ({ profiles, onProfileClick }) => {
  const restaurantRef = useRef<THREE.Group>(null);

  useFrame((state) => {
    if (restaurantRef.current) {
      restaurantRef.current.position.y = Math.sin(state.clock.elapsedTime * 0.4) * 0.08;
    }
  });

  const restaurantProfiles = profiles.slice(2, 5);

  return (
    <group ref={restaurantRef}>
      {/* Floor */}
      <Box
        position={[0, -0.5, 0]}
        args={[22, 1, 22]}
        receiveShadow
      >
        <meshLambertMaterial color="#8B4513" />
      </Box>

      {/* Restaurant Building */}
      <group position={[0, 3, -6]}>
        {/* Main Building */}
        <Box
          position={[0, 0, 0]}
          args={[8, 6, 4]}
          castShadow
          receiveShadow
        >
          <meshLambertMaterial color="#CD853F" />
        </Box>

        {/* Roof */}
        <Box
          position={[0, 3.5, 0]}
          args={[9, 1, 5]}
          castShadow
        >
          <meshLambertMaterial color="#8B0000" />
        </Box>

        {/* Restaurant Sign */}
        <group position={[0, 4.5, 2.1]}>
          <Box args={[4, 1, 0.1]}>
            <meshLambertMaterial color="#FFD700" />
          </Box>
          <Text
            position={[0, 0, 0.1]}
            fontSize={0.35}
            color="#8B0000"
            anchorX="center"
            anchorY="middle"
          >
            浪漫西餐厅
          </Text>
        </group>

        {/* Large Windows */}
        <Box
          position={[-2.5, 1, 2.1]}
          args={[2, 2.5, 0.1]}
        >
          <meshLambertMaterial color="#87CEEB" opacity={0.8} transparent />
        </Box>
        <Box
          position={[2.5, 1, 2.1]}
          args={[2, 2.5, 0.1]}
        >
          <meshLambertMaterial color="#87CEEB" opacity={0.8} transparent />
        </Box>

        {/* Entrance */}
        <Box
          position={[0, -1, 2.1]}
          args={[1.5, 4, 0.1]}
        >
          <meshLambertMaterial color="#654321" />
        </Box>

        {/* Door Handle */}
        <Sphere
          position={[0.5, -1, 2.15]}
          args={[0.05]}
          castShadow
        >
          <meshLambertMaterial color="#FFD700" />
        </Sphere>
      </group>

      {/* Dining Tables */}
      {[
        [-4, 0, 3],
        [4, 0, 3],
        [-4, 0, 0],
        [4, 0, 0],
        [0, 0, 5]
      ].map((position, index) => (
        <group key={`table-${index}`} position={position as [number, number, number]}>
          {/* Table */}
          <Box
            position={[0, 0.7, 0]}
            args={[1.2, 0.1, 1.2]}
            castShadow
            receiveShadow
          >
            <meshLambertMaterial color="#FFFFFF" />
          </Box>
          
          {/* Table Legs */}
          {[[-0.5, -0.5], [0.5, -0.5], [-0.5, 0.5], [0.5, 0.5]].map((legPos, legIndex) => (
            <Cylinder
              key={`leg-${legIndex}`}
              position={[legPos[0], 0.35, legPos[1]]}
              args={[0.03, 0.03, 0.7, 8]}
              castShadow
            >
              <meshLambertMaterial color="#654321" />
            </Cylinder>
          ))}

          {/* Table Setting */}
          <group position={[0, 0.8, 0]}>
            {/* Plates */}
            <Cylinder
              position={[-0.3, 0.01, -0.2]}
              args={[0.15, 0.15, 0.02, 16]}
              castShadow
            >
              <meshLambertMaterial color="#FFFFFF" />
            </Cylinder>
            <Cylinder
              position={[0.3, 0.01, 0.2]}
              args={[0.15, 0.15, 0.02, 16]}
              castShadow
            >
              <meshLambertMaterial color="#FFFFFF" />
            </Cylinder>

            {/* Wine Glasses */}
            <Cylinder
              position={[-0.1, 0.05, 0.1]}
              args={[0.04, 0.03, 0.1, 8]}
              castShadow
            >
              <meshLambertMaterial color="#87CEEB" transparent opacity={0.9} />
            </Cylinder>
            <Cylinder
              position={[0.1, 0.05, -0.1]}
              args={[0.04, 0.03, 0.1, 8]}
              castShadow
            >
              <meshLambertMaterial color="#87CEEB" transparent opacity={0.9} />
            </Cylinder>

            {/* Interactive Candle */}
            <InteractiveCandle position={[0, 0.08, 0]} />
          </group>

          {/* Chairs */}
          {[
            [-0.8, 0, 0],
            [0.8, 0, 0],
            [0, 0, -0.8],
            [0, 0, 0.8]
          ].map((chairPos, chairIndex) => (
            <group key={`chair-${chairIndex}`} position={chairPos as [number, number, number]}>
              {/* Seat */}
              <Box
                position={[0, 0.4, 0]}
                args={[0.4, 0.05, 0.4]}
                castShadow
              >
                <meshLambertMaterial color="#8B4513" />
              </Box>
              {/* Back */}
              <Box
                position={[0, 0.7, -0.15]}
                args={[0.4, 0.6, 0.05]}
                castShadow
              >
                <meshLambertMaterial color="#8B4513" />
              </Box>
              {/* Legs */}
              {[[-0.15, -0.15], [0.15, -0.15], [-0.15, 0.15], [0.15, 0.15]].map((legPos, legIdx) => (
                <Cylinder
                  key={`chair-leg-${legIdx}`}
                  position={[legPos[0], 0.2, legPos[1]]}
                  args={[0.02, 0.02, 0.4, 8]}
                  castShadow
                >
                  <meshLambertMaterial color="#654321" />
                </Cylinder>
              ))}
            </group>
          ))}
        </group>
      ))}

      {/* Bar Counter */}
      <group position={[-8, 0, -2]}>
        <Box
          position={[0, 1, 0]}
          args={[2, 0.2, 6]}
          castShadow
          receiveShadow
        >
          <meshLambertMaterial color="#8B4513" />
        </Box>
        
        {/* Bar Stools */}
        {[-2, 0, 2].map((pos, index) => (
          <group key={`stool-${index}`} position={[1.2, 0, pos]}>
            <Cylinder
              position={[0, 0.6, 0]}
              args={[0.2, 0.2, 0.05, 8]}
              castShadow
            >
              <meshLambertMaterial color="#8B4513" />
            </Cylinder>
            <Cylinder
              position={[0, 0.3, 0]}
              args={[0.03, 0.03, 0.6, 8]}
              castShadow
            >
              <meshLambertMaterial color="#654321" />
            </Cylinder>
          </group>
        ))}

        {/* Interactive Wine Bottles on Bar */}
        {[
          { pos: -1.5, color: '#228B22' },
          { pos: -0.5, color: '#FF4500' },
          { pos: 0.5, color: '#4169E1' },
          { pos: 1.5, color: '#FFD700' }
        ].map((bottle, index) => (
          <RotatingWine 
            key={`bottle-${index}`}
            position={[0, 1.3, bottle.pos]} 
            color={bottle.color}
          />
        ))}
      </group>

      {/* Decorative Plants */}
      {[
        [-6, 0, 7],
        [6, 0, 7],
        [-9, 0, 2],
        [9, 0, 2]
      ].map((position, index) => (
        <group key={`decoration-${index}`} position={position as [number, number, number]}>
          <Cylinder
            position={[0, 0.4, 0]}
            args={[0.3, 0.25, 0.8, 8]}
            castShadow
            receiveShadow
          >
            <meshLambertMaterial color="#8B4513" />
          </Cylinder>
          <Sphere
            position={[0, 1, 0]}
            args={[0.5]}
            castShadow
          >
            <meshLambertMaterial color="#228B22" />
          </Sphere>
        </group>
      ))}

      {/* Hanging Lights */}
      {[
        [-3, 4, 1],
        [3, 4, 1],
        [0, 4, 3]
      ].map((position, index) => (
        <group key={`light-${index}`} position={position as [number, number, number]}>
          <Cylinder
            args={[0.02, 0.02, 1, 8]}
          >
            <meshLambertMaterial color="#654321" />
          </Cylinder>
          <Sphere
            position={[0, -0.7, 0]}
            args={[0.2]}
          >
            <meshLambertMaterial color="#FFF8DC" emissive="#FFF8DC" emissiveIntensity={0.3} />
          </Sphere>
        </group>
      ))}

      {/* Floating Hearts */}
      {Array.from({ length: 6 }, (_, i) => (
        <group
          key={`heart-${i}`}
          position={[
            (Math.random() - 0.5) * 18,
            3 + Math.random() * 2,
            (Math.random() - 0.5) * 18
          ]}
        >
          <Text
            fontSize={0.4}
            color="#FF69B4"
            anchorX="center"
            anchorY="middle"
          >
            ♥
          </Text>
        </group>
      ))}

      {/* Profile Bubbles */}
      {restaurantProfiles.map((profile, index) => {
        const positions: [number, number, number][] = [
          [-4, 2, 3],
          [4, 2, 3],
          [0, 2, 5]
        ];
        
        return (
          <ProfileBubble
            key={profile.id}
            profile={profile}
            position={positions[index]}
            onClick={() => onProfileClick(profile)}
            color="#FF6B6B"
          />
        );
      })}
    </group>
  );
};